﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace BasicCMS.Data
{
    public class DeleteBuilder : IPersistentBuilder
    {
        private readonly IUnitOfWork unitOfWork;
        private IList<KeyValuePair<string, object>> parameters = new List<KeyValuePair<string, object>>();
        private string tableName;
        private string condition;
        private IDbCommand command;

        public DeleteBuilder(IUnitOfWork unitOfWork, string tableName)
        {
            this.unitOfWork = unitOfWork;
            this.tableName = tableName;
        }

        public DeleteBuilder Where(string condition)
        {
            this.condition = condition;
            return this;
        }

        public DeleteBuilder Param(string name, object value)
        {
            parameters.Add(new KeyValuePair<string, object>(name, value));
            return this;
        }

        void IPersistentBuilder.Persistent()
        {
            StringBuilder sqlBuilder = new StringBuilder();
            sqlBuilder.AppendFormat("DELETE FROM [{0}]", tableName);
            if (!String.IsNullOrEmpty(condition))
            {
                sqlBuilder.AppendFormat(" WHERE {0}", condition);
                foreach (var param in parameters)
                {
                    command.Parameters.Add(new SqlParameter("@" + param.Key, param.Value));
                }
            }
            command.CommandText = sqlBuilder.ToString();
            command.ExecuteNonQuery();
        }

        IDbCommand IPersistentBuilder.Command
        {
            set { command = value; }
        }

        bool IPersistentBuilder.IsValid
        {
            get { return !String.IsNullOrEmpty(tableName) && parameters.Count > 0; }
        }
    }
}
